package com.youboy.wechatapi.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.elasticsearch.index.query.BoolFilterBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.youboy.searchapi.api.CompanyService;
import com.youboy.searchapi.api.ProductService;
import com.youboy.searchapi.domain.Company;
import com.youboy.searchapi.domain.Product;
import com.youboy.wechatapi.service.bind.BindService;

@Controller
public class VipController {

	private Logger log = Logger.getLogger(VipController.class);
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private BindService bindService; 
	
	@RequestMapping(value = "/vip/show", produces = { "text/html;charset=utf-8" })
	public String show(Model model, HttpSession session, 
			@RequestParam(value = "openid", required = false) String openid){
		session.removeAttribute("pageNo");
		session.removeAttribute("pageSize");
		
		session.setAttribute("openid", openid);
		return "vip/vip-show";
	}

	/**
	 * 确认请求来自微信服务器
	 * 
	 * @param model
	 * @param signature 微信加密签名
	 * @param timestamp 时间戳
	 * @param nonce 随机数
	 * @param echostr  随机字符串
	 * @return
	 */
	@RequestMapping(value = "/vip/list", produces = { "text/html;charset=utf-8" })
	//@ResponseBody
	public String list(Model model, HttpSession session,
			@RequestParam(value = "pageNo") Integer pageNo,
		@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		
		if(pageNo == null || pageNo <= 0){
			pageNo = 1;
		}
		
		if(pageSize == null || pageSize <= 0){
			pageSize = 10;
		}
		
		Object pageObj = session.getAttribute("pageNo");
		if(pageObj != null){
			int no = Integer.valueOf(pageObj.toString());
			if(pageNo <= no){
				log.info("pageNo < nowNo ,can't get data!");
				return "vip/vip-no";
			}
		}
		
		List<String> bindPage = null;
		try {
			bindPage = bindService.getBindInfo(pageNo, pageSize);
		} catch (Exception e) {
			log.error("[pageNo:" + pageNo + "][pageSize:" + pageSize + "] get bindInfo by page error !", e);
		}
		
		if(bindPage == null || bindPage.size() == 0){
			log.error("[pageNo:" + pageNo + "][pageSize:" + pageSize + "] get bindInfo by page fail , the size is 0 !");
			return "vip/vip-no";
		}
		
		Map<Company, List<Product>> data = this.getData(bindPage);
		
		model.addAttribute("vipData", data);
		session.setAttribute("pageNo", pageNo);
		session.setAttribute("pageSize", pageSize);
		
		//return resultJson;
		return "vip/vip-list";
	}
	
	private Map<Company, List<Product>> getData(List<String> usList){
		BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
		// 根据关键词获取
		boolQuery.must(QueryBuilders.inQuery(Company.Fields.username,usList.toArray()));
		// 过滤没有log的数据
		BoolFilterBuilder filter = FilterBuilders.boolFilter()
				.must(FilterBuilders.termFilter(Company.Fields.status, 0))
				.mustNot(FilterBuilders.termFilter(Company.Fields.logo, ""));

		List<Company> companyList = null;

		try {
			companyList = this.companyService.search(boolQuery, filter, 0, 10);
		} catch (Exception e) {
			log.error(" get companyList fail ! ", e);
		}
		
		return this.getProductList(companyList);
	}
	
	private Map<Company, List<Product>> getProductList(List<Company> companyList){
		BoolQueryBuilder proBoolQuery = QueryBuilders.boolQuery();
		
		// 过滤没有图片的数据
		BoolFilterBuilder proFilter = FilterBuilders.boolFilter().mustNot(
				FilterBuilders.termFilter(Product.Fields.thumbImg, ""));
		
		Map<Company, List<Product>> data = new HashMap<Company, List<Product>>(); 
		if(companyList == null || companyList.size() == 0){
			return null;
		}
		
		List<Company> removeList = new ArrayList<Company>();
		for (Company company : companyList) {
			proBoolQuery = QueryBuilders.boolQuery();
			// 根据关键词获取
			proBoolQuery.must(QueryBuilders.fieldQuery(Product.Fields.username,company.getUsername()));

			List<Product> productList = null;
			try {
				productList = this.productService.search(proBoolQuery, proFilter, 0, 3);
			} catch (Exception e) {
				log.error("get productList fail ! ", e);
			}
			
			if (productList != null && productList.size() > 0) {
				data.put(company, productList);
			} else {
				removeList.add(company);
			}
		}
		
		for (Company company : removeList) {
			companyList.remove(company);
		}
		
		return data;
	}
}
